package cn.dt.ymcc.service.impl;

import cn.dt.ymcc.domain.Login;
import cn.dt.ymcc.domain.WechatDto;
import cn.dt.ymcc.mapper.LoginMapper;
import cn.dt.ymcc.result.JSONResult;
import cn.dt.ymcc.service.ILoginService;
import cn.dt.ymcc.util.AssertUtil;
import cn.dt.ymcc.util.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author whale.dai
 * @since 2022-07-15
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {
    @Autowired
    private LoginMapper logininfoMapper;
    // %s代表占位符需要替换的内容
    public final String TOKEN_URL = "http://localhost:10040/oauth/token?client_id=%s&client_secret=%s&grant_type=password&redirect_uri=http://www.baidu.com&username=%s&password=%s";
    public final String REFRESHTOKEN_URL = "http://localhost:10040/oauth/token?grant_type=refresh_token&refresh_token=%s&client_id=%s&client_secret=%s";
    /**
     * 三方微信登录
     * @param dto
     * @return
     */
    @Override
    public JSONResult wechat(WechatDto dto) {
//        String tokenUrl = BaseConstants.WeChart.TOKEN_URL
//                .replace("APPID",BaseConstants.WeChart.APPID)
//                .replace("SECRET",BaseConstants.WeChart.SECRET)
//                .replace("CODE",dto.getCode());
//
//        //将网址中对应的appid，secret，code替换
////        tokenUrl.replace("APPID",appId);
////        tokenUrl.replace("SECRET",secret);
////        tokenUrl.replace("CODE",code);
//        String getTokenstr = HttpClientUtils.httpGet(tokenUrl);
//        //将字符串形式的getTokenstr解析成json格式
//        JSONObject jsonObject = JSONObject.parseObject(getTokenstr);
//        //获取到token
//        String accessToken = jsonObject.getString("access_token");
//        String openId = jsonObject.getString("openid");
//        //2.通过openid查询wxuser表是否存在
//        Wxuser wxuser = wxuserMapper.loadByOpenid(openId);
//        // 2,1存在，直接登录
//        //2.通过wxuser表
//        if(wxuser!=null &&wxuser.getUserId()!=null){
//            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
//            //4.1 存储redis
////            String token = UUID.randomUUID().toString();
////            redisTemplate.opsForValue().set(
////                    token,
////                    logininfo,//对象要序列化
////                    30,
////                    TimeUnit.MINUTES
////            );
////            //4.2 返回token + logininfo
////            Map<String, Object> map = new HashMap<>();
////            map.put("token",token);
////            //我们是高级技师，应该考虑到一些敏感信息不要返回给前端
////            logininfo.setSalt(null);
////            logininfo.setPassword(null);
////            map.put("logininfo",logininfo);
//
//            return AjaxResult.me().setResultObj(loginSuccessHandler(logininfo));
//        }
//        // 2.2，不存在则跳转到注册界面,网页要带token+openid
//        String binderParam = "?accessToken="+accessToken+"&openId="+openId;
//        return AjaxResult.me().setSuccess(false).setResultObj(binderParam);
        return JSONResult.success();
//
    }

    @Override
    public JSONResult common(Login login) {
        //1.账号要存在
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username",login.getUsername());
        Login loginTmp = selectOne(wrapper);
        AssertUtil.isNotNull(loginTmp,"用户不存在！！");
        //2.拼接请求，去使用密码模式换取token
        Integer type = login.getType();
        String clientId = "website";//客户端是主站
        String clientSecret = "123";
        if(type.intValue() == 0){//客户端是后台
            clientId = "admin";
            clientSecret="123";
        }
        String url = String.format(TOKEN_URL,clientId,clientSecret,login.getUsername(),login.getPassword());
        String resultStr = HttpUtil.sendPost(url, null);
        System.out.println(resultStr);
        Map<String,Object> resutlMap = JSONObject.parseObject(resultStr, Map.class);
        //3.拿到值响应给前端
        if(resutlMap.containsKey("error_description")){//获取token失败
            return JSONResult.error(resutlMap.get("error_description").toString());
        }else{
            Integer expires_in = (Integer)resutlMap.get("expires_in");//多少毫秒后过期
            resutlMap.put("expiresTime",System.currentTimeMillis() + expires_in);
            return JSONResult.success(resutlMap);
        }
    }

    /**
     * http://localhost:10040/oauth/token?grant_type=refresh_token&refresh_token=%s&client_id=%s&client_secret=%s
     * @param login
     * @return
     */
    @Override
    public JSONResult refresh(Login login) {
//        //1.账号要存在
//        Wrapper<Login> wrapper = new EntityWrapper<>();
//        wrapper.eq("username",login.getUsername());
//        Login loginTmp = selectOne(wrapper);
//        AssertUtil.isNotNull(loginTmp,"用户不存在！！");
//        //2.拼接请求，去使用密码模式换取token
//        Integer type = login.getType();
//        String clientId = "website";//客户端是主站
//        String clientSecret = "123";
//        if(type.intValue() == 0){//客户端是后台
//            clientId = "admin";
//            clientSecret="123";
//        }
//        String url = String.format(REFRESHTOKEN_URL,login.getRefreshToken(),clientSecret,login.getUsername(),login.getPassword());
//        String resultStr = HttpUtil.sendPost(url, null);
//        Map<String,Object> resutlMap = JSONObject.parseObject(resultStr, Map.class);
//        //3.拿到值响应给前端
//        if(resutlMap.containsKey("error_description")){//获取token失败
//            return JSONResult.error(resutlMap.get("error_description").toString());
//        }else{
//            Integer expires_in = (Integer)resutlMap.get("expires_in");//多少毫秒后过期
//            resutlMap.put("expiresTime",System.currentTimeMillis() + expires_in);
//            return JSONResult.success(resutlMap);
//        }
        return JSONResult.success();
    }

}
